import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/comic_user_model.dart';
import '../providers/auth_provider.dart';
import '../theme/app_theme.dart';
import '../widgets/login_dialog.dart';

class AuthUtils {
  /// 检查用户是否已登录，如果未登录则显示登录弹窗
  static bool checkLoginAndShowDialog(BuildContext context, WidgetRef ref) {
    final isLoggedIn = ref.read(authProvider).isLoggedIn;

    if (!isLoggedIn) {
      showLoginDialog(context);
      return false;
    }

    return true;
  }

  /// 显示登录弹窗
  static void showLoginDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const LoginDialog(),
    );
  }

  /// 显示登录弹窗（可点击外部关闭）
  static void showLoginDialogDismissible(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) => const LoginDialog(),
    );
  }

  /// 需要登录的操作包装器
  static void requireLoginAction(
    BuildContext context,
    WidgetRef ref,
    VoidCallback action,
  ) {
    if (checkLoginAndShowDialog(context, ref)) {
      action();
    }
  }

  /// 异步操作的登录检查包装器
  static Future<void> requireLoginActionAsync(
    BuildContext context,
    WidgetRef ref,
    Future<void> Function() action,
  ) async {
    if (checkLoginAndShowDialog(context, ref)) {
      await action();
    }
  }

  /// 退出登录
  static Future<void> logout(WidgetRef ref) async {
    await ref.read(authProvider.notifier).logout();
  }

  /// 获取当前登录用户的邮箱
  static String getCurrentUserEmail(WidgetRef ref) {
    return ref.read(authProvider).userEmail;
  }

  /// 检查是否已登录（不显示弹窗）
  static bool isLoggedIn(WidgetRef ref) {
    return ref.read(authProvider).isLoggedIn;
  }

  /// 获取用户信息
  static UserData? getUserInfo(WidgetRef ref) {
    return ref.read(authProvider).userInfo;
  }

  /// 显示客服联系弹窗
  static void showCustomerServiceDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        const supportEmail = 'zengx493@gmail.com';

        return Dialog(
          backgroundColor: Colors.transparent,
          child: Container(
            width: MediaQuery.of(context).size.width * 0.85,
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: const Color(0xFF2A1F3D), // 修改背景色
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.3), // 增强阴影
                  blurRadius: 15,
                  offset: const Offset(0, 8),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // Close button
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      'Customer Support',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.white, // 修改为白色文字
                      ),
                    ),
                    GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Container(
                        padding: const EdgeInsets.all(6),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.1), // 修改关闭按钮背景
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.close,
                          color: Colors.white70, // 修改图标颜色
                          size: 18,
                        ),
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 20),

                // Support icon
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: const Color(0xFF7FFFD4).withOpacity(0.2),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.support_agent,
                    color: AppTheme.buttonBgColor, // 调整图标颜色更亮
                    size: 40,
                  ),
                ),

                const SizedBox(height: 16),

                // Description text
                const Text(
                  'If you have any questions, please contact us through:',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.white70, // 修改为白色文字
                  ),
                  textAlign: TextAlign.center,
                ),

                const SizedBox(height: 20),

                // Email display
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.1), // 修改邮箱容器背景
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(
                      color: Colors.white.withOpacity(0.2), // 修改边框颜色
                    ),
                  ),
                  child: const Row(
                    children: [
                      const Icon(
                        Icons.email,
                        color: AppTheme.buttonBgColor, // 保持邮箱图标颜色
                        size: 20,
                      ),
                      SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          supportEmail,
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.white, // 修改邮箱文字颜色
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),

                const SizedBox(height: 20),

                // Action buttons
                Row(
                  children: [
                    // Copy email button
                    Expanded(
                      child: ElevatedButton.icon(
                        onPressed: () async {
                          await Clipboard.setData(
                            const ClipboardData(text: supportEmail),
                          );
                          if (context.mounted) {
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('Email copied to clipboard'),
                                backgroundColor: Colors.green,
                                duration: Duration(seconds: 2),
                              ),
                            );
                          }
                        },
                        icon: const Icon(
                          Icons.copy,
                          size: 18,
                        ),
                        label: const Text(
                          'Copy',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor:
                              Colors.white.withOpacity(0.15), // 修改复制按钮背景
                          foregroundColor: Colors.white, // 修改按钮文字颜色
                          elevation: 0,
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 12,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                            side: BorderSide(
                              color: Colors.white.withOpacity(0.2), // 添加边框
                            ),
                          ),
                        ),
                      ),
                    ),

                    const SizedBox(width: 12),

                    // Send email button
                    Expanded(
                      child: ElevatedButton.icon(
                        onPressed: () async {
                          final Uri emailUri = Uri(
                            scheme: 'mailto',
                            path: supportEmail,
                            query:
                                'subject=ToonZen App Feedback&body=Please describe your issue here...',
                          );

                          try {
                            if (await canLaunchUrl(emailUri)) {
                              await launchUrl(emailUri);
                            } else {
                              if (context.mounted) {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  const SnackBar(
                                    content: Text(
                                        'Cannot open email app, please send email manually'),
                                    backgroundColor: Colors.orange,
                                  ),
                                );
                              }
                            }
                          } catch (e) {
                            if (context.mounted) {
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  content: Text('Failed to open email app'),
                                  backgroundColor: Colors.red,
                                ),
                              );
                            }
                          }
                        },
                        icon: const Icon(
                          Icons.send,
                          size: 18,
                          color: Colors.white,
                        ),
                        label: const Text(
                          'Send',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppTheme.buttonBgColor, // 修改发送按钮颜色
                          foregroundColor: Colors.white, // 按钮文字使用深色
                          elevation: 2,
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 12,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
